import re
from users.models import User
from django.contrib.auth.backends import ModelBackend
# user = None
# 只要你采用了jwt的认证,登录成功之后,会调用此方法,此方法就把认证的用户信息传递过来了


def jwt_response_payload_handler(token, user=None, request=None):
    """
    自定义jwt认证成功返回数据
    """
    return {
        'token': token,
        'user_id': user.id,
        'username': user.username
    }


# 1.原有的认证方式不能满足需求,因此要找到原有的认证方式

# 2.输入手机号/用户名,因为手机号和用户名是一一对应的关系,所以根据手机号找到用户名
# account -->手机号/用户名
def get_user_by_account(account):
    try:
        if re.match(r'1[3-9]\d{9}', account):
            # 手机号
            user = User.objects.get(mobile=account)
        else:
            # 用户名
            user = User.objects.get(username=account)
    except User.DoesNotExist:
        user = None

    return user

# 3.根据查询的用户信息去检测密码是否正确


class UsernameMobileAuth(ModelBackend):

    def authenticate(self, request, username=None, password=None, **kwargs):

        user = get_user_by_account(username)

        if user is not None and user.check_password(password):
            # 没有问题返回用户信息
            return user

        return None


class SettingsBackend(object):

    def authenticate(self, request, username=None, password=None):

        user = get_user_by_account(username)

        if user is not None and user.check_password(password):
            return user
        return None

    # 继承object的类需要多实现一个方法,get_user(self,user_id)
    def get_user(self,user_id):
        try:
            return User.objects.get(pk=user_id)
        except User.DoesNotExist:
            return None
